package com.xb.loan.encryptor.mina.decoder;


import com.xb.loan.encryptor.bean.Packet;
import com.xb.loan.util.binaryConvert.parse.ParsePointer;
import com.xb.loan.util.binaryConvert.parse.str.StringParser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.demux.MessageDecoder;
import org.apache.mina.filter.codec.demux.MessageDecoderResult;

import java.util.LinkedList;
import java.util.List;

public class BinaryDecoder implements MessageDecoder {

	private Log LOG = LogFactory.getLog(BinaryDecoder.class);
	
	private StringParser parser = new StringParser();

	@Override
	public MessageDecoderResult decodable(IoSession session, IoBuffer buf) {

		LOG.debug("buf size : " + buf.remaining());
		
		if (buf.prefixedDataAvailable(2)) {
			
			return MessageDecoderResult.OK;
		} else {
			
			return MessageDecoderResult.NEED_DATA;
		}
	}

	@Override
	public MessageDecoderResult decode(IoSession session, IoBuffer buf,
			ProtocolDecoderOutput out) throws Exception {
		
		LOG.debug("decode buf size : " + buf.remaining());
		
		Packet p = new Packet();
		// 包总长度
		p.setLen(buf.getShort());
		
		p.setProtocolMajor(buf.get());
		
		p.setProtocolMinor(buf.get());
		
		byte[] data = new byte[buf.remaining()];
		
		buf.get(data);
		
		ParsePointer pointer = new ParsePointer(0);
		// transcode
		p.setTranscode(parser.convert(data, pointer, null, null));
		
		List<Byte> packetBody = new LinkedList<Byte>();
		
		for(int i=pointer.getPointer();i<data.length;i++){
			
			packetBody.add(data[i]);
		}
		
		p.setPacketBody(packetBody);
		
		out.write(p);
		
		return MessageDecoderResult.OK;
	}

	@Override
	public void finishDecode(IoSession arg0, ProtocolDecoderOutput arg1)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
